﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using PMS.ReportViewer;

namespace PMS.ChucNang
{
    public partial class XuatKhoEntry : FormEntryBase
    {
        #region Constants
        private const string PRODUCT_NOT_EXIST = "PRODUCT_NOT_EXIST";
        private const string INVALID_QUANTITY = "INVALID_QUANTITY";
        private const string QTY_NOT_GREAT_THAN = "QTY_NOT_GREAT_THAN";
        private const string DUPLICATE_PRODUCT_CODE = "DUPLICATE_PRODUCT_CODE";
        private const string CHITITENHAP_DONOT_EXISTED = "CHITITENHAP_DONOT_EXISTED";
        private const string MUST_FILL_HANDUNG_OR_HANSUDUNG = "MUST_FILL_HANDUNG_OR_HANSUDUNG";

        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string BINDING_PROPERTY = "EditValue";
        #endregion

        #region Private Members
        BaseEntityCollection<ChiTietPhieuXuat> m_DetailItemsList;
        private List<ComboItemExp> m_KhoList;
        protected SanPhamBO m_ProductService;
        protected PhieuXuatBO m_Service;
        protected PhieuGiaoHangBO m_GiaoService;
        protected ChiTietPhieuXuatBO m_ChiTietService;

        protected bool m_isDuplicateProduct { get; set; }
        #endregion

        #region Properties
        protected Entity.PhieuXuat CurrentNhapKhoEntry
        {
            get
            {
                return base.Entity as Entity.PhieuXuat;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public PhieuGiaoHangBO GiaoService
        {
            get
            {
                if (m_GiaoService == null)
                {
                    m_GiaoService = new PhieuGiaoHangBO();
                }
                return m_GiaoService;
            }
        }

        public PhieuXuatBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new PhieuXuatBO();
                }
                return m_Service;
            }
        }

        public SanPhamBO ProductService
        {
            get
            {
                if (m_ProductService == null)
                {
                    m_ProductService = new SanPhamBO();
                }
                return m_ProductService;
            }
        }

        public ChiTietPhieuXuatBO ChiTietService
        {
            get
            {
                if (m_ChiTietService == null)
                {
                    m_ChiTietService = new ChiTietPhieuXuatBO();
                }
                return m_ChiTietService;
            }
        }
        #endregion

        #region Constructors
        public XuatKhoEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            m_DetailItemsList = new BaseEntityCollection<ChiTietPhieuXuat>();
            BindingToGrid();
            loadDatasourceCbbKho();
        }

        private void InitStyle()
        {
            //grid
            grdDetail.CausesValidation = false;
            bteMaPN.Tag = "Ignore";
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;

            this.grvDetail.OptionsView.ShowFooter = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsView.ShowGroupPanel = false;
            this.grvDetail.OptionsCustomization.AllowColumnMoving = false;
            this.grvDetail.OptionsCustomization.AllowGroup = false;
            this.grvDetail.OptionsMenu.EnableColumnMenu = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsNavigation.EnterMoveNextColumn = true;
            this.grvDetail.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;
            this.grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            cbbMaKho.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cbbMaKho.Properties.ReadOnly = true;
            txtTongTien.Properties.ReadOnly = true;

            //filed color
            txtSoHD.BackColor = REQUIRED_FIELD_COLOR;
            dteNgayNhap.BackColor = REQUIRED_FIELD_COLOR;
            bteNhaCC.BackColor = REQUIRED_FIELD_COLOR;
            cbbMaKho.BackColor = REQUIRED_FIELD_COLOR;

            //Mask
            txtTongTien.Properties.Mask.MaskType = MaskType.Numeric;
            txtTongTien.Properties.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            txtTongTien.Properties.Mask.UseMaskAsDisplayFormat = true;

            spdColSoLuong.Mask.MaskType = MaskType.Numeric;
            spdColSoLuong.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            spdColSoLuong.Mask.UseMaskAsDisplayFormat = true;

            calColDonGia.Mask.MaskType = MaskType.Numeric;
            calColDonGia.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            calColDonGia.Mask.UseMaskAsDisplayFormat = true;

            txtColGiaTrungThau.Mask.MaskType = MaskType.Numeric;
            txtColGiaTrungThau.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColGiaTrungThau.Mask.UseMaskAsDisplayFormat = true;

            txtColTotal.Mask.MaskType = MaskType.Numeric;
            txtColTotal.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColTotal.Mask.UseMaskAsDisplayFormat = true;

            this.bteMaPN.Properties.MaxLength = 14;
            this.txtSoHD.Properties.MaxLength = 12;
            this.bteNhaCC.Properties.MaxLength = 6;
            this.txtNguoiLap.Properties.MaxLength = 35;
            this.txtNguoiNhap.Properties.MaxLength = 35;
            this.txtLyDo.Properties.MaxLength = 200;
            this.txtGhiChu.Properties.MaxLength = 300;

            this.txtSoPG.Properties.ReadOnly = true;
            this.txtSoHDG.Properties.ReadOnly = true;
            this.txtPTG.Properties.ReadOnly = true;
            this.txtNguoiGiao.Properties.ReadOnly = true;
            this.dteNgayGiao.Properties.ReadOnly = true;
            this.txtNguoiNhan.Properties.ReadOnly = true;
            this.txtKhachHangNhan.Properties.ReadOnly = true;
            this.txtPTTT.Properties.ReadOnly = true;
            this.txtGhiChuGiao.Properties.ReadOnly = true;

            this.txtSoPG.BackColor = DISABLE_FIELD_COLOR;
            this.txtSoHDG.BackColor = DISABLE_FIELD_COLOR;
            this.txtPTG.BackColor = DISABLE_FIELD_COLOR;
            this.txtNguoiGiao.BackColor = DISABLE_FIELD_COLOR;
            this.dteNgayGiao.BackColor = DISABLE_FIELD_COLOR;
            this.txtNguoiNhan.BackColor = DISABLE_FIELD_COLOR;
            this.txtKhachHangNhan.BackColor = DISABLE_FIELD_COLOR;
            this.txtPTTT.BackColor = DISABLE_FIELD_COLOR;
            this.txtGhiChuGiao.BackColor = DISABLE_FIELD_COLOR;
        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentNhapKhoEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteMaPN.DataBindings.Clear();
            this.txtSoHD.DataBindings.Clear();
            this.bteNhaCC.DataBindings.Clear();
            this.txtNguoiLap.DataBindings.Clear();
            this.dteNgayLap.DataBindings.Clear();
            this.txtNguoiNhap.DataBindings.Clear();
            this.dteNgayNhap.DataBindings.Clear();
            this.txtLyDo.DataBindings.Clear();
            this.txtGhiChu.DataBindings.Clear();


            this.bteMaPN.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.SoPX.ToString());
            this.txtSoHD.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.SoHD.ToString());
            this.bteNhaCC.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.MaKH.ToString());
            this.txtNguoiLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NguoiLap.ToString());
            this.dteNgayLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NgayLapPhieu.ToString());
            this.txtNguoiNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NguoiXuat.ToString());
            this.dteNgayNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NgayXuatKho.ToString());
            this.txtLyDo.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.LyDoXuat.ToString());
            this.txtGhiChu.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.GhiChu.ToString());

            PhieuXuat pn = entity as PhieuXuat;
            m_DetailItemsList.Clear();
            m_DetailItemsList.AddRange(ChiTietService.GetAllChiTietPhieuXuatBySoPX(pn.SoPX));
            BindingToGrid();
            SetKhoCbbData(pn.MaKho);

            PhieuGiaoHang phieugiao = GiaoService.GetPhieuGiaoHangBySoPX(pn.SoPX);


            if (phieugiao != null)
            {

                chkPhieuGiao.Checked = true;
                chkPhieuGiao.Properties.ReadOnly = true;
            }
            else
            {
                phieugiao = new PhieuGiaoHang();
                chkPhieuGiao.Checked = false;
                chkPhieuGiao.Properties.ReadOnly = true;
            }

            this.txtSoPG.DataBindings.Clear();
            this.txtSoHDG.DataBindings.Clear();
            this.txtPTG.DataBindings.Clear();
            this.txtNguoiGiao.DataBindings.Clear();
            this.dteNgayGiao.DataBindings.Clear();
            this.txtNguoiNhan.DataBindings.Clear();
            this.txtKhachHangNhan.DataBindings.Clear();
            this.txtPTTT.DataBindings.Clear();
            this.txtGhiChuGiao.DataBindings.Clear();

            this.txtSoPG.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.SoPG.ToString());
            this.txtSoHDG.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.SoHD.ToString());
            this.txtPTG.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.PhuongThucGiao.ToString());
            this.txtNguoiGiao.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.NguoiGiao.ToString());
            this.dteNgayGiao.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.NgayGiao.ToString());
            this.txtNguoiNhan.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.NguoiNhan.ToString());
            this.txtKhachHangNhan.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.MaKH.ToString());
            this.txtPTTT.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.PhuongThucTT.ToString());
            this.txtGhiChuGiao.DataBindings.Add(BINDING_PROPERTY, phieugiao, PhieuGiaoHangColumns.GhiChu.ToString());

            if (pn.SoPX == NEW_String)
            {
                CanPrint = false;
            }
            else
            {
                CanPrint = true;
            }

            if (m_DetailItemsList.Count > 0)
            {
                long total = 0;
                foreach (ChiTietPhieuXuat item in m_DetailItemsList)
                {

                    total = total + item.Total;
                }
                txtTongTien.EditValue = total;
            }

            
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.txtSoHD.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();

            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new DateValidateRule(true,true));
            SetValidator(validate, dteNgayNhap);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, txtSoHD);
            

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new CustomerValidationRules(null, true));
            SetValidator(validate, bteNhaCC);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new InventoryValidationRules(null, true));
            SetValidator(validate, cbbMaKho);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new PhieuXuatValidateRule(NEW_String, false));
            SetValidator(validate, bteMaPN);

        }

        public override void New()
        {
            this.CurrentNhapKhoEntry = new Entity.PhieuXuat
                {
                    NgayLapPhieu = Constants.BUSINESS_DATE,
                    NgayXuatKho = Constants.BUSINESS_DATE,
                    SoPX = NEW_String,
                    MaKho = "KHO01"
                };
            txtTongTien.EditValue = 0;
            base.New();
        }

        public override void IsNewChanged()
        {
            if (IsNew)
            {
                CanPrint = false;
                grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                colMaThuoc.OptionsColumn.ReadOnly = false;
                colSolo.OptionsColumn.ReadOnly = false;
                bteColMaThuoc.Buttons[0].Enabled = true;
                bteColSolo.Buttons[0].Enabled = true;
                dteNgayNhap.Enabled = true;
            }
            else
            {
                CanPrint = true;
                grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                colMaThuoc.OptionsColumn.ReadOnly = true;
                colSolo.OptionsColumn.ReadOnly = true;
                bteColMaThuoc.Buttons[0].Enabled = false;
                bteColSolo.Buttons[0].Enabled = false;
                dteNgayNhap.Enabled = false;
            }
        }

        protected override bool Save()
        {
            try
            {
                ChiTietPhieuXuats detailList = new ChiTietPhieuXuats();
                detailList.AddRange(m_DetailItemsList);
                if (detailList.Count <= 0)
                {
                    MessageBox.Show(this, "Vui lòng nhập vào thông tin Chi Tiết Phiếu Xuất", "Chú ý", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                if (IsNew)
                {
                    CurrentNhapKhoEntry = Service.CreatePhieuXuat(CurrentNhapKhoEntry, detailList);
                }
                else
                {
                    Service.UpdatePhieuXuat(CurrentNhapKhoEntry, detailList);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()  //do not allow delete PhieuXuat
        {
            //try
            //{
            //    Service.DeletePhieuXuat(CurrentNhapKhoEntry);
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    ShowErrorMessage(ex);
            //    return false;
            //}
            MessageBox.Show(this, "Bạn không thể thực hiện được thao tác xóa Phiếu Xuất", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override void Print()
        {
            try
            {
                PhieuXuatKhoViewer xutViewer = new PhieuXuatKhoViewer(CurrentNhapKhoEntry.SoPX);
                xutViewer.StartPosition = FormStartPosition.CenterParent;
                xutViewer.WindowState = FormWindowState.Maximized;



                PhieuGiaoHang pg = GiaoService.GetPhieuGiaoHangBySoPX(CurrentNhapKhoEntry.SoPX);

                if (pg != null)
                {
                    DialogResult result = MessageBox.Show(Messages.GetString("CoInPhieuGiaoHangKhong"), Messages.GetString(Constants.TITLE_CONFIRM_MESSAGE), MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        PhieuGiaoHangViewer giaoViewer = new PhieuGiaoHangViewer(pg.SoPG);
                        giaoViewer.StartPosition = FormStartPosition.CenterParent;
                        giaoViewer.WindowState = FormWindowState.Maximized;
                        xutViewer.ShowDialog();
                        giaoViewer.ShowDialog();
                    }
                    else
                    {
                        xutViewer.ShowDialog();
                    }
                }
                else
                {
                    xutViewer.ShowDialog();
                }

            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void BindingToGrid()
        {
            grdDetail.DataSource = m_DetailItemsList;
            colMaThuoc.FieldName = LuuKhoColumns.MaThuoc.ToString();
            colSoLuong.FieldName = ChiTietPhieuXuatColumns.SoLuong.ToString();
            colDonGia.FieldName = ChiTietPhieuXuatColumns.DonGia.ToString();
            colGiaTrungThau.FieldName = ChiTietPhieuXuatColumns.GiaTrungThau.ToString();
            colSolo.FieldName = LuuKhoColumns.SoLo.ToString();
            colTotal.FieldName = ChiTietPhieuXuatColumns.Total.ToString();
        }

        private void LoadingProductToGrid(SanPham loadingProduct)
        {
            ChiTietPhieuXuat getRow = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            grvDetail.SetFocusedRowCellValue(colSoLuong, 0);
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadingLuuKhoToGrid(LuuKho loadingProduct)
        {
            ChiTietPhieuXuat getRow = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            getRow.SoLo = loadingProduct.SoLo;
            getRow.MaLuuKho = loadingProduct.MaLuuKho;
            grvDetail.SetFocusedRowCellValue(colSoLuong, 0);
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            getRow.TonKho = loadingProduct.TonKho;
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentNhapKhoEntry.SoPX = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentNhapKhoEntry.SoPX = code;
                        Entity = CurrentNhapKhoEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuXuat();
                            CurrentNhapKhoEntry.SoPX = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentNhapKhoEntry.SoPX = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuXuat();
                            CurrentNhapKhoEntry.SoPX = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }

        private void loadDatasourceCbbKho()
        {
            KhoHangs list = (new KhoHangBO()).GetAllKhoHang();
            m_KhoList = new List<ComboItemExp>();
            foreach (var item in list)
            {
                ComboItemExp tem = new ComboItemExp();
                tem.DisplayValue = item.TenKho;
                tem.ItemValue = item.MaKho;
                m_KhoList.Add(tem);
            }

            cbbMaKho.Properties.Items.AddRange(m_KhoList);
        }

        private void SetKhoCbbData(string code)
        {
            cbbMaKho.SelectedItem = m_KhoList.Find(o => o.ItemValue.ToString().Equals(code, StringComparison.CurrentCultureIgnoreCase));
        }
        #endregion

        private void bteMaPN_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new XuatKhoLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.PhieuXuatSelected != null)
                    {
                        LoadObjectOnForm(bteMaPN.Text.Trim(), form.PhieuXuatSelected.SoPX, form.PhieuXuatSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaPN_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteMaPN.Text) && !IsNew)
                {
                    New();
                }
                else
                {
                    if (CurrentNhapKhoEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentNhapKhoEntry.SoPX);
                    string code = DataConvertUltils.ToString(bteMaPN.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        PhieuXuat temPhieuXuat = Service.GetPhieuXuatByID(code);
                        LoadObjectOnForm(previousCode, code, temPhieuXuat);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaKho_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            InventoryLookup form = new InventoryLookup();
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.InventorySelected != null)
                {
                    CurrentNhapKhoEntry.MaKho = form.InventorySelected.MaKho;
                }
            }
        }

        private void bteNhaCC_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            CustomerLookup form = new CustomerLookup();
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.CustomerSelected != null)
                {
                    CurrentNhapKhoEntry.MaKH = form.CustomerSelected.MaKH;
                }
            }
        }

        private void bteNhaCC_Leave(object sender, EventArgs e)
        {
            try
            {
                string code = DataConvertUltils.ToString(bteNhaCC.EditValue);
                KhachHang ncc = (new KhachHangBO()).GetKhachHangByID(code);
                if (ncc != null)
                {
                    CurrentNhapKhoEntry.MaKH = ncc.MaKH;
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            ChiTietPhieuXuat row = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            if (e.Column == colDonGia || e.Column == colSoLuong)
            {
            }
        }

        private void grvDetail_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if ((e.Info.IsRowIndicator) && (e.RowHandle >= 0))
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void grvDetail_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void grvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                    if (this.grvDetail.IsRowSelected(this.grvDetail.FocusedRowHandle) == true)
                    {
                        ChiTietPhieuXuat row = (ChiTietPhieuXuat)this.grvDetail.GetRow(grvDetail.FocusedRowHandle);
                        int index = this.m_DetailItemsList.IndexOf(row);
                        if (index != -1)
                        {
                            bool isNewRow = (row.RowStatus == (byte)RowStatus.New);

                            this.m_DetailItemsList.RemoveAt(index);
                            if (isNewRow == true)
                            {
                                this.m_DetailItemsList.RemoveRows.Remove(row);
                            }
                            base.IsDataChanged = true;


                            decimal total = 0;
                            foreach (ChiTietPhieuXuat item in m_DetailItemsList)
                            {
                                total = total + item.Total;
                            }
                            txtTongTien.EditValue = total;
                        }
                    }
                
            }
            else if (e.KeyCode == Keys.F3)
            {
                if (this.grvDetail.FocusedColumn == this.colMaThuoc)
                {
                    bteColMaThuoc_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColMaThuoc.Buttons[0]));
                }
                else if (this.grvDetail.FocusedColumn == colSolo)
                {
                    bteColSolo_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColSolo.Buttons[0]));
                }
            }
        }

        private void grvDetail_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ChiTietPhieuXuat row = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            if (row == null)
            {
                if (grvDetail.FocusedColumn != colMaThuoc)
                {
                    e.Cancel = true;
                }

            }
            else
            {
                if (string.IsNullOrEmpty(row.MaThuoc))
                {
                    if (grvDetail.FocusedColumn != colMaThuoc)
                    {
                        e.Cancel = true;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(row.SoLo))
                    {
                        if (grvDetail.FocusedColumn == colMaThuoc || grvDetail.FocusedColumn == colSolo)
                        {
                            e.Cancel = false;
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }
                    else
                    {
                        e.Cancel = false;
                    }
                }
            }

        }

        private void grvDetail_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ChiTietPhieuXuat currentRow = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            DevExpress.XtraGrid.Columns.GridColumn errorColumn = null;
            if (currentRow != null)
            {
                if (currentRow.SoLuong <= 0)
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colSoLuong, Messages.GetString(INVALID_QUANTITY));
                    errorColumn = colSoLuong;
                }

                if (string.IsNullOrEmpty(currentRow.MaThuoc))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colMaThuoc, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = colMaThuoc;
                }
                else
                {
                    SanPham tempProduct = ProductService.GetSanPhamByID(currentRow.MaThuoc);
                    if (tempProduct == null)
                    {
                        e.Valid = false;
                        grvDetail.SetColumnError(colMaThuoc, Messages.GetString(PRODUCT_NOT_EXIST));
                        errorColumn = colMaThuoc;
                    }
                }

                if (string.IsNullOrEmpty(currentRow.SoLo))
                {
                    e.Valid = false;
                    grvDetail.SetColumnError(colSolo, Messages.GetString(Constants.REQUIRE_FIELD));
                    errorColumn = colSolo;
                }
                else
                {
                    if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    {
                        int duplicate = -1;
                        int index = m_DetailItemsList.IndexOf(currentRow);
                        if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                        {
                            for (int i = 0; i < m_DetailItemsList.Count; i++)
                            {
                                ChiTietPhieuXuat temprow = m_DetailItemsList[i];
                                if (temprow.MaLuuKho==currentRow.MaLuuKho && index != i)
                                {
                                    duplicate = i;
                                }
                            }
                        }

                        if (duplicate >= 0)
                        {
                            grvDetail.SetColumnError(colSolo, string.Format(Messages.GetString(DUPLICATE_PRODUCT_CODE),duplicate+1));
                            e.Valid = false;
                            errorColumn = colSolo;
                            m_isDuplicateProduct = true;
                        }
                        else
                        {
                            m_isDuplicateProduct = false;
                        }
                    }
                }
            }
            if (errorColumn != null)
            {
                grvDetail.FocusedColumn = errorColumn;
            }
            else
            {
                decimal total = 0;
                foreach (ChiTietPhieuXuat item in m_DetailItemsList)
                {
                    total = total + item.Total;
                }
                txtTongTien.EditValue = total;
            }
        }

        //method check validate values in gridview when enter/modify data in cell
        private void grvDetail_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            ChiTietPhieuXuat row = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            if (grvDetail.FocusedColumn == colSoLuong)
            {
                int qty = DataConvertUltils.ToInt(e.Value);
                if (qty <= 0)
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(INVALID_QUANTITY);
                }
                else
                {
                    if (IsNew)
                    {
                        if (qty > row.TonKho)
                        {
                            e.Valid = false;
                            string message = string.Format(Messages.GetString(QTY_NOT_GREAT_THAN), row.TonKho);
                            e.ErrorText = message;
                        }
                    }
                    else  //if update SoLuong greater than (old SoLuong + TonKho)
                    {
                        LuuKho lk = (new LuuKhoBO()).GetLuuKhoByMaThuocAndSoLoAndMaKHo(row.MaThuoc, row.SoLo, CurrentNhapKhoEntry.MaKho);
                        if (qty > (row.SoLuong + lk.TonKho))
                        {
                            e.Valid = false;
                            string message = string.Format(Messages.GetString(QTY_NOT_GREAT_THAN), (row.SoLuong + lk.TonKho));
                            e.ErrorText = message;
                        }
                    }
                }
            }
            else if (grvDetail.FocusedColumn == colMaThuoc)
            {
                string productCode = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(productCode))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    SanPham temProduct = ProductService.GetSanPhamByID(productCode);
                    if (temProduct == null)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(PRODUCT_NOT_EXIST);
                    }
                    else
                    {
                        e.Value = temProduct.MaThuoc;
                        LoadingProductToGrid(temProduct);
                    }
                }
            }
            else if (grvDetail.FocusedColumn == colSolo)
            {
                string solo = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(solo))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    LuuKho lk = (new LuuKhoBO()).GetLuuKhoByMaThuocAndSoLoAndMaKHo(row.MaThuoc, solo,CurrentNhapKhoEntry.MaKho);
                    if (lk != null)
                    {
                        LoadingLuuKhoToGrid(lk);
                    }
                    else
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(CHITITENHAP_DONOT_EXISTED);
                    }
                    //if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    //{
                    //    int duplicate = -1;
                    //    int index = m_DetailItemsList.IndexOf(row);
                    //    if (m_DetailItemsList != null && m_DetailItemsList.Count > 0 && e.Valid)
                    //    {
                    //        for (int i = 0; i < m_DetailItemsList.Count; i++)
                    //        {
                    //            ChiTietPhieuNhap temprow = m_DetailItemsList[i];
                    //            if (temprow.MaCTPN.Equals(row.MaCTPN, StringComparison.CurrentCultureIgnoreCase) && index != i)
                    //            {
                    //                duplicate = i;
                    //            }
                    //        }
                    //    }

                    //    if (duplicate >= 0)
                    //    {
                    //        e.ErrorText = string.Format(Messages.GetString(DUPLICATE_PRODUCT_CODE), duplicate + 1);
                    //        e.Valid = false;
                    //        m_isDuplicateProduct = true;
                    //    }
                    //    else
                    //    {
                    //        m_isDuplicateProduct = false;
                    //    }
                    //}
                }
            }
        }

        private void bteColMaThuoc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ProductLookup form = new ProductLookup(true);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.ProductSelected != null)
                {
                    LoadingProductToGrid(form.ProductSelected);
                }
            }
        }

        private void bteMaPN_Enter(object sender, EventArgs e)
        {
            if (bteMaPN.Text.Equals(NEW_String))
            {
                bteMaPN.Text = string.Empty;
            }
        }

        private void grvDetail_DataSourceChanged(object sender, EventArgs e)
        {
            decimal total = 0;
            foreach (ChiTietPhieuXuat item in m_DetailItemsList)
            {
                total = total + item.Total;
            }
            txtTongTien.EditValue = total;

        }

        private void cbbMaKho_SelectedValueChanged(object sender, EventArgs e)
        {
            CurrentNhapKhoEntry.MaKho = (string)((ComboItemExp)cbbMaKho.SelectedItem).ItemValue;
        }

        private void bteColSolo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ChiTietPhieuXuat row = grvDetail.GetFocusedRow() as ChiTietPhieuXuat;
            if (row != null)
            {
                LuuKhoLookup form = new LuuKhoLookup(CurrentNhapKhoEntry.MaKho, row.MaThuoc,null,0);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.LuuKhoSelected != null)
                    {
                        LoadingLuuKhoToGrid(form.LuuKhoSelected);
                    }
                }
            }
        }

        private void chkPhieuGiao_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void dteNgayLap_Leave(object sender, EventArgs e)
        {
            if (dteNgayLap.IsModified)
            {
                CurrentNhapKhoEntry.NgayLapPhieu = dteNgayLap.DateTime;
            }
        }

        private void dteNgayNhap_Leave(object sender, EventArgs e)
        {
            if (dteNgayNhap.IsModified)
            {
                CurrentNhapKhoEntry.NgayXuatKho = dteNgayNhap.DateTime;
            }
        }
    }
}
